package com.kelai.service.impl;

import com.kelai.common.IRepository;
import com.kelai.common.exception.BreezeeException;
import com.kelai.domain.*;
import com.kelai.repository.IMarketActivityRepository;
import com.kelai.service.IMarketService;
import javafx.util.Callback;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;

import java.util.*;

/**
 * 市场活动服务实现类
 * Created by luffy on 2017/05/16.
 */
@Service("marketService")
public class DefaultMarketService implements IMarketService {

    private final IMarketActivityRepository marketActivityRepository;

    private final JdbcTemplate jdbcTemplate;

    private final PlatformTransactionManager transactionManager;

    @Autowired
    public DefaultMarketService(IMarketActivityRepository marketActivityRepository, JdbcTemplate jdbcTemplate, PlatformTransactionManager transactionManager) {
        this.marketActivityRepository = marketActivityRepository;
        this.jdbcTemplate = jdbcTemplate;
        this.transactionManager = transactionManager;
    }

    @Override
    public IRepository<MarketActivityEntity> getRepository() {
        return marketActivityRepository;
    }

    @Override
    public MarketActivityEntity saveInfo(MarketActivityEntity r, Callback<MarketActivityEntity, Object>... callback) throws BreezeeException {
        MarketActivityEntity a = getRepository().saveEntity(r, callback);
        if (r.getCustomers() != null) {
            saveMarkets(a.getId() , r.getCustomers());
        }
        return a;
    }

    @Override
    public void saveMarkets(String pkId , List<CustomerEntity> ces) {

        String delSqlMarAll = "delete from R_CUS_MAR where MAR_ID = '"+pkId+"'";
        String insertSql = "insert into R_CUS_MAR (CUS_ID,MAR_ID) values(?,?)";
        List<Object[]> insertList = new ArrayList<>();
        if (ces != null) {
            ces.forEach(a -> {
                insertList.add(new Object[]{a.getId(), pkId});
            });
        }
        jdbcTemplate.update(delSqlMarAll);
        if (insertList.size() > 0)
            jdbcTemplate.batchUpdate(insertSql, insertList);
    }

}
